<?php

namespace App\Console\Commands;

use App\Models\WeekCheckout;
use App\Models\WeekProfitReturn;
use Illuminate\Console\Command;
use Large\Zhengdada\Functions;
use App\Models\AdminUser;
use App\Handlers\WeekProfitReturnHandler;
use Cache;
use Config;
use App\Jobs\WeekProfitReturnJob;


class WeekProfitReturnCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:weekprofitreturn';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户周返佣金计算';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \Log::channel('week_checkouts')->info('用户周返佣金计算：'.date('Y-m-d H:i:s'));
        // 周1至6
        list($t1, $t2) = [getStartOfWeek(), getEndOfWeek(6)];

        $user = Cache::remember('users', 3600, function () {
            return AdminUser::whereHas('roles', function ($q) {
                $q->where('id', 2);
            })->with('users_leader')->get();
        });

        $newUser = changeUserTjrId($user);
        $res     = Functions::getTreeData($newUser, Config::get('app.zon_id'), 'tjr_id');
        $res     = array_values(collect($res)->sortByDesc('level')->toArray());

        $weekprofitreturn = WeekProfitReturn::whereBetween('created_at', [$t1, $t2])->get();
        $week_checkout    = WeekCheckout::whereBetween('created_at', [$t1, $t2])->get();
        $newUser          = Cache::get('users');

        foreach ($res as $k => $v) {
            $weekprofit = $weekprofitreturn->where('user_id', $v['id'])->first();
            $userXj     = $newUser->where('tjr_id', $v['id'])->first();
            $week       = $week_checkout->where('user_id', $v['id'])->first();

            if ($userXj && !$weekprofit && $week) { //判断是否有下级，是否处理过
                try {
                    WeekProfitReturnHandler::zituishoushuyinli($v);
                } catch (\Exception $e) {
                    \Log::channel('week_checkouts')->info(json_encode($v));
                }
            }

            // 循环完后 触发队列
            if ($newUser->count() == $k + 1) {
                dispatch(new WeekProfitReturnJob(900));
            }
        }
    }
}
